<template>
  <view class="home-page" :style="{ 'background-image': `url(${home_bg})` }">
    <view class="top-wrap" :style="{ 'padding-top': `${MBTop}px` }">
      <view
        class="top-title"
        :style="{
          height: `${MBHeight}px`,
          'line-height': `${MBHeight}px`,
          'margin-bottom': '18rpx'
        }"
      >
        习惯百日行
      </view>
      <view class="main-tabs">
        <view
          class="main-tabs-item"
          :class="{ active: mainType }"
          @tap="handleMainType(1)"
        >
          推荐打卡
        </view>
        <view
          class="main-tabs-item"
          :class="{ active: !mainType }"
          @tap="handleMainType(0)"
        >
          今日任务
        </view>
      </view>
    </view>
    <view v-show="mainType" class="content-wrap">
      <view
        class="home-swiper"
        :class="{ 'swiper-hidden': !swiperShow || !bannerList.length }"
      >
        <swiper
          class="swiper-wrap"
          indicator-color="rgba(255, 255, 255, .5)"
          indicator-active-color="rgba(255, 255, 255, 1)"
          :duration="500"
          :interval="3000"
          :circular="true"
          :autoplay="true"
          :indicator-dots="true"
        >
          <swiper-item v-for="(item, idx) in bannerList" :key="idx">
            <image
              :lazy-load="true"
              :src="item.img_url"
              class="slide-image"
              @tap="handleBanner(item)"
            />
          </swiper-item>
        </swiper>
      </view>
      <view v-if="hasHabitActivity" class="sub-tabs">
        <view
          class="sub-tabs-item"
          :class="{ active: activity_type }"
          @tap="handleSubType(1)"
        >
          百日行
        </view>
        <view
          class="sub-tabs-item"
          :class="{ active: !activity_type }"
          @tap="handleSubType(0)"
        >
          热门打卡
        </view>
      </view>
      <scroll-view
        class="list-scroll"
        :scroll-y="true"
        :lower-threshold="100"
        :refresher-enabled="true"
        refresher-default-style="none"
        refresher-background="none"
        :scroll-anchoring="true"
        :refresher-triggered="refresherTriggered"
        @scroll="scrollList"
        @scrollToLower="scrollToLowerList"
        @refresherRefresh="refresherRefresh"
      >
        <view v-if="refresherTriggered" class="loading">
          下拉刷新中...
        </view>
        <view class="list-content">
          <border-box
            v-for="n in activityLists"
            :key="n.id"
            :inside-padding="16"
            class="border-box-use"
          >
            <view class="list-item" @tap="goAvtivityDetail(n.id)">
              <view class="item-left">
                <view class="title">
                  {{ n.activity_title }}
                </view>
                <view v-if="n.activity_type === 1" class="time">
                  {{ n.start_time }}-{{ n.end_time }}
                </view>
                <view class="desc">
                  {{ n.activity_describe }}
                </view>
                <view class="join">
                  <view class="avatar">
                    <avatar-group
                      :avatar="n.avatar"
                      :height="44"
                      :avatar-limit-len="7"
                    />
                  </view>
                  <view class="text">
                    <view class="light">
                      {{ n.join_num > 9999 ? "9999+" : n.join_num }}
                    </view>
                    <view>人已参与</view>
                  </view>
                </view>
              </view>
              <view class="item-right">
                <image :lazy-load="true" :src="n.activity_intro_img" />
              </view>
            </view>
          </border-box>
          <view v-if="!activityLists.length" class="empty-wrap">
            <image
              :lazy-load="true"
              class="empty-pic"
              :src="activity_offline"
            />
            <view class="main">
              该城市暂无活动
            </view>
          </view>
          <view v-if="isEnd && activityLists.length" class="loading not-more">
            没有更多了
          </view>
        </view>
      </scroll-view>
      <!-- <view
        class="list-content"
        style="height: calc(100% - 44px);"
      >
        <view
          v-for="n in 20"
          :key="n"
          class="home-swiper"
        >
          list-item
        </view>
      </view> -->
      <!-- </view> -->
    </view>
    <!-- </scroll-view> -->
    <scroll-view
      v-show="!mainType"
      class="today-content-wrap"
      :scroll-y="true"
      :refresher-enabled="true"
      refresher-default-style="none"
      refresher-background="none"
      :refresher-triggered="refresherTriggered"
      @refresherRefresh="refresherRefresh"
    >
      <view class="list-content">
        <border-box class="border-box-use" :inside-padding="16">
          <view
            class="top-item"
            :style="{ 'background-image': `url(${today_libai})` }"
          >
            <view class="time-title">
              {{ todayInfo.date }}
            </view>
            <view class="week">
              {{ todayInfo.week }}
            </view>
            <view class="desc">
              {{ todayInfo.tips }}
            </view>
            <view
              v-if="todayInfo.clock_log.length"
              class="check-in"
              :class="{ 'check-in-todo': todayInfo.no_clock_num > 0 }"
              :style="{
                'background-image': `url(${
                  todayInfo.no_clock_num > 0 ? today_pen : ''
                })`
              }"
            >
              {{ todayCheckTips }}
            </view>
          </view>
        </border-box>
        <view v-if="todayInfo.clock_log.length">
          <border-box
            v-for="n in todayInfo.clock_log"
            :key="n.id"
            :inside-padding="16"
            class="border-box-use"
          >
            <view class="list-item">
              <view class="item-left">
                <view class="time">
                  {{ n.clock_time }}
                </view>
                <view class="desc"> 活动：{{ n.activity_title }} </view>
                <view class="theme"> 主题：{{ n.theme_title }} </view>
              </view>
              <view class="item-right">
                <view
                  class="btn"
                  :class="{ dis: n.status }"
                  :style="{ 'background-image': `url(${today_btn})` }"
                  @tap="clockIn(n.id)"
                >
                  {{ n.status ? "已" : "去" }}打卡
                </view>
              </view>
            </view>
          </border-box>
        </view>
        <view v-else>
          <view
            class="today-empty"
            :style="{ 'background-image': `url(${today_empty})` }"
          >
            你还没有参与打卡哦，去首页看看吧～
          </view>
          <view
            class="today-empty-btn"
            :style="{ 'background-image': `url(${today_btn2})` }"
            @tap="mainType = 1"
          >
            去看看
          </view>
        </view>
      </view>
    </scroll-view>
    <contactTeacher v-if="mainType" :isReQequest.sync="isReQequest" />
    <AwardGive :show.sync="showAward" :position="'index'" />
    <!-- <cover-image
      v-if="
      main-type-
      class="teacher-btn-img"
      :src="teacher_btn"
      @tap="handleChange"
    />
    <AtCurtain
      :is-opened="isOpened"
      :on-close="onClose"
    >
      <view class="teacher-pop">
        <view class="title">
          联系老师
        </view>
        <view class="text">
          扫码添加老师 获取1对1服务
        </view>
        <view class="img-wrap">
          <image :lazy-load="true"
            class="QR-code"
            :src="receiveTeacher.qrcode_url"
          />
        </view>
      </view>
    </AtCurtain> -->
  </view>
</template>

<script>
import {
  home_bg,
  today_libai,
  today_pen,
  today_btn,
  today_btn2,
  today_empty
} from "@/libs/image-url";
import {
  bannerList,
  hasHabitActivity,
  activityLists,
  todayInfo
} from "_api/home";
import basicDataSet from "@/config/basic-data-set";
import Taro from "@tarojs/taro";
import globalData from "@/libs/globalData";
import borderBox from "_c/border-box/index";
import contactTeacher from "_c/contact-teacher/index";
import avatarGroup from "_c/avatar-group";
// 按需引入, 更小的应用体积
import { AtDivider } from "taro-ui-vue";
import "./index.scss";
import { activity_offline } from "@/libs/image-url";
import AwardGive from "@/components/award-give/index.vue";

const CHECK_TIPS_TEXT = "棒！你已完成今日所有打卡任务~";
export default {
  components: {
    borderBox,
    contactTeacher,
    avatarGroup,
    AwardGive
  },
  data() {
    return {
      home_bg,
      today_libai,
      today_pen,
      today_btn,
      today_btn2,
      today_empty,
      activity_offline,
      MBTop: 0,
      MBHeight: 0,
      mainType: 1,
      activity_type: 1,
      show: false,
      isOpened: false,
      mainWrapCanScroll: true,
      listCanScroll: false,
      swiperShow: true,
      query: {
        city_id: "",
        grade_id: ""
      },
      isEnd: false,
      bannerList: [],
      hasHabitActivity: 0,
      activityLists: [],
      page: 1,
      refresherTriggered: false,
      todayInfo: {
        clock_log: []
      },
      todayCheckTips: CHECK_TIPS_TEXT,
      today: 0,
      showAward: false,
      isReQequest: false
    };
  },
  computed: {
    // query() {
    //   return {
    //     city_id: Taro.getStorageSync("city_id"),
    //     grade_id: Taro.getStorageSync("grade_id")
    //   };
    // }
    /**标题距离顶部的高度 */
    titleToTopDistanceStyle() {
      /**
       * 18rpx为top-title元素的marginBottom
       * 125rpx为main-tabs元素的整体高度
       *
       */
      return {
        height: `calc(100% - ${this.MBTop + this.MBHeight}px - 18rpx - 125rpx)`,
        width: "100%"
      };
    }
  },
  async onLoad(opt) {
    this.query = {
      city_id: Taro.getStorageSync("city_id"),
      grade_id: Taro.getStorageSync("grade_id")
    };
    this.MBHeight = globalData.getData("MBHeight");
    this.MBTop = globalData.getData("MBTop");
    console.log(this.titleToTopDistance);
    // this.getgGradeId();
    // this.getCityId();
    //临时
    // this.getTodayInfo()
  },
  async onShow() {
    /* 储存邀请id */
    this.getParams.login_invite_id &&
      Taro.setStorageSync("login_invite_id", this.getParams.login_invite_id);

    Taro.eventCenter.once("handleGetIsLogin", data => {
      this.mainType = data;
    });
    this.query = {
      city_id: Taro.getStorageSync("city_id"),
      grade_id: Taro.getStorageSync("grade_id")
    };
    this.today = ~~Taro.getStorageSync("today");
    /**重新获取联系老师 */
    this.isReQequest = true;

    this.getBannerList();
    await this.getHasHabitActivity();
    this.today && this.handleMainType(this.today ? 0 : 1);
    !this.today && this.handleMainType(this.mainType);
    !!Taro.getStorageSync("token") && (this.showAward = true);
    !Taro.getStorageSync("token") && (this.todayInfo = { clock_log: [] });
  },
  onHide() {
    console.log("onhhhduishdusud");
    Taro.removeStorageSync("today");
  },
  methods: {
    getBannerList() {
      bannerList(this.query).then(r => {
        this.bannerList = r.data;
      });
    },
    handleBanner(item) {
      console.log(item);
      switch (item.link_type) {
        case "1": {
          Taro.navigateTo({
            url: `/pages/web-view/index?url=${item.link_url}`
          });
        }
        case "2": {
          // Taro.navigateTo({
          //   url: item.link_url
          // });
        }
        default: {
          return;
        }
      }
    },
    // getTeacher() {
    //   receiveTeacher(this.query).then(r => {
    //     this.receiveTeacher = r.data;
    //   });
    // },
    getHasHabitActivity() {
      return hasHabitActivity(this.query).then(r => {
        this.hasHabitActivity = r.data.has_habit_activity;
        !this.hasHabitActivity && (this.activity_type = 0);
      });
    },
    getActivityLists(page, refresh) {
      let query = {
        activity_type: this.activity_type,
        page,
        ...this.query
      };
      return activityLists(query).then(({ data }) => {
        if (refresh) {
          this.activityLists = data.data;
        } else {
          this.activityLists.push(...data.data);
        }
        this.isEnd =
          data.meta.pagination.current_page >= data.meta.pagination.total_pages;
        !this.isEnd && (this.page = data.meta.pagination.current_page + 1);
      });
    },
    scrollList({ detail: { scrollTop } }) {
      if (scrollTop > 50) {
        this.swiperShow = false;
      } else {
        this.swiperShow = true;
      }
    },
    scrollToLowerList(e) {
      if (this.isEnd) {
        return;
      }
      this.getActivityLists(this.page);
    },
    async refresherRefresh() {
      this.refresherTriggered = true;
      this.mainType && (await this.getActivityLists(1, true));
      !this.mainType && (await this.getTodayInfo());
      this.refresherTriggered = false;
    },
    handleMainType(type) {
      this.mainType = type;
      this.mainType && this.getActivityLists(1, true);
      !this.mainType && this.getTodayInfo();
    },
    getTodayInfo() {
      return todayInfo().then(r => {
        this.todayInfo = r.data.data;
        // this.todayInfo.clock_log = []
        this.todayCheckTips =
          this.todayInfo.no_clock_num > 0
            ? `今日还有${
                this.todayInfo.no_clock_num > 999
                  ? "999+"
                  : this.todayInfo.no_clock_num
              }项未打卡哦`
            : CHECK_TIPS_TEXT;
      });
    },
    handleSubType(type) {
      this.activity_type = type;
      // console.log(this.$refs.listScroll)
      this.getActivityLists(1, true);
    },
    goAvtivityDetail(id) {
      console.log(id);
      Taro.navigateTo({
        url: `/pages/activity-detail/index?id=${id}`
      });
    },
    clockIn(id) {
      Taro.setStorageSync("comeFromToday", 1);
      Taro.navigateTo({
        url: `/pages/theme-detail/index?id=${id}`
      });
    }
  }
};
</script>
